package com.common.util;

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

public class FileUtils {

    /**
     * 文件上传到服务器绝对
     *
     * @param uploadPath  上传文件夹路劲-配置文件配置
     * @param moduleName  模块名称
     * @param file        要上传的文件
     * @param newFileName 要保存的文件名
     * @return
     */
    public static String fileUpload(String uploadPath, String moduleName, MultipartFile file, String newFileName) {
        try {
            File saveFile = new File(uploadPath + "/" + moduleName);
            if (!saveFile.exists()) {
                // 创建目录
                boolean mkdirs = saveFile.mkdirs();
            }
            // 设置存放图片文件的路径
            String path = uploadPath + "/" + moduleName + "/" + newFileName;
            //数据库文件保存路径
            String pictureUrl = moduleName + "/" + newFileName;
            // 转存文件到指定的路径
            File tempFile = new File(path);
            org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
            //返回项目模块名+文件名
            return pictureUrl;
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @param uploadPath
     * @param moduleName
     * @param file
     * @param newFileName
     * @param fileTypes
     * @return
     */
    public static String fileUpload(String uploadPath, String moduleName, MultipartFile file, String newFileName, String[] fileTypes) {

        return "";
    }

    public static boolean deleteOneFile(String realPath) {
        boolean flag = false;
        File file = new File(realPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 将一个base64转换成图片保存在  path文件夹下  ,命名随机
     *
     * @param base64String
     * @param path         是一个文件夹路径
     * @param
     * @throws Exception
     */
    public static String savePictoServer(String base64String, String path) throws Exception {

        BASE64Decoder decoder = new BASE64Decoder();  //此类需引入的jar包
        //要把+在上传时变成的空格再改为+
        base64String = base64String.replaceAll(" ", "+");
        //去掉“data:image/png;base64,”后面才是base64编码，去掉之后才能解析
        base64String = base64String.replace("data:image/jpeg;base64,", "");
        //在本地指定位置建立文件夹，path由控制台那边进行定义
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String uuidImg = UUID.randomUUID().toString() + ".png";
        String fileName = path + uuidImg;
        try {
            byte[] buffer = decoder.decodeBuffer(base64String);
            OutputStream os = new FileOutputStream(fileName);
            for (int i = 0; i < buffer.length; ++i) {
                if (buffer[i] < 0) {//调整异常数据
                    buffer[i] += 256;
                }
            }
            os.write(buffer);
            os.close();
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return uuidImg;
    }

    /**
     * 读取图片在本地存储的位置
     *
     * @param imgFile
     * @throws Exception
     */
    public static String getImageStr(String imgFile) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    public static String getFileMd5(String filePath) {
        URL url = null;
        String urlString = "";
        try {
            url = new URL(filePath);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String current;
            while ((current = in.readLine()) != null) {
                urlString = current;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return urlString;
    }


    public static void writeFileMd5(String urlPath,String filePath) {
        URL url = null;
        try {
            FileInputStream in = new FileInputStream(new File(filePath));
            url = new URL(urlPath);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            DataOutputStream ou = new DataOutputStream(connection.getOutputStream());
            byte[] buffer = new byte[4096];
            int count = 0;
            while ((count = in.read(buffer)) > 0) {
                ou.write(buffer, 0, count);
            }
            ou.flush();
            ou.close();
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static String getFileMsg(String filePath) {
        String lineTxt = null;
        try {
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                while (br.read() != -1) {
                    lineTxt = br.readLine();
                }
                br.close();
            } else {
                System.out.println("文件不存在!");
            }
        } catch (Exception e) {
            System.out.println("文件读取错误!");
        }
        return lineTxt;
    }

    public static void writeFileMsg(String filePath, String message) {
        File file = new File(filePath);
        BufferedWriter bw = null;
        try {
            FileWriter fw = new FileWriter(file, true);
            bw = new BufferedWriter(fw);
            bw.newLine();
            bw.write(message);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
